package org.xtremeobjects.forms.ui.editors;

import javax.naming.OperationNotSupportedException;

import org.xtremeobjects.domain.model.Clazz;
import org.xtremeobjects.domain.model.ddd.Repository;

public class ObjectEditorModel {

	private Clazz clazzModel;
	private Repository repository;
	private Object currentObject;
	private Object objectId;

	public ObjectEditorModel(Clazz clazz, Repository repository, Object objectId) {
		this.clazzModel = clazz;
		this.repository = repository;
		this.objectId = objectId;
		currentObject = null;
	}

	public Clazz getClazz() {
		return clazzModel;
	}

	public void setCurrentObject(Object current) {
		currentObject = current;
	}

	Object getCurrentObject() {
		if(currentObject==null)
			currentObject = loadObject();
		return currentObject;
	}

	private Object loadObject() {
		if(objectId!=null)
			currentObject = repository.findObjectById(objectId.toString());
		else
			currentObject = repository.allInstances().iterator().next();//Just used to test

		return currentObject;
	}

	public Class getImplementationClass() {
		return clazzModel.getImplementationClass();
	}

	public String[] getPropertyNames() {
		return clazzModel.getPropertiesNames();
	}

	public void save() throws OperationNotSupportedException {
		repository.updateObject(getCurrentObject());
	}

}
